/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package webservices;

import Entities.Activereservation;
import Entities.User;
import constants.Consts;
import helpers.Debug;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;
import javax.ws.rs.Path;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import rhserver.MainController;

/**
 * REST Web Service
 *
 * @author Bari
 */
@Path("resourcedetails")
public class GetResourceDetails extends AbstractWebService {

    public GetResourceDetails() throws Exception {
        super();
    }

    private Activereservation jpaGetActivation(long resourceId, EntityManager em) {
        TypedQuery<Activereservation> query = em.createNamedQuery("Activereservation.findByResourceid", Activereservation.class);
        query.setParameter("resourceid", resourceId);
        List<Activereservation> reservations = query.getResultList();
        if (reservations.size() > 0) {
            return reservations.get(0);
        }
        return null;
    }

    @Override
    protected String processJsonMessage(String jsonMessage) {
        JSONObject response = new JSONObject();
        EntityManager em = MainController.getInstance().getEntityManager();
        try {
            Debug.logMessage("processJsonMessage", "Current TIme: " + MainController.getInstance().getCurrentDate().toGMTString());
            JSONObject receivedJson = new JSONObject(jsonMessage);
            long resourceId = receivedJson.getLong(Consts.RESOURCE_ID);
            String userAndroidId = receivedJson.getString(Consts.USER_ID);

            Activereservation reservation = jpaGetActivation(resourceId, em);
            User user = getLocalUser(userAndroidId, em);
            if (reservation != null) {

                long currentServerTime = MainController.getInstance().getCurrentDate().getTime();
                long clientTime = receivedJson.getLong(Consts.CLIENT_TIME);
                long reservationLength = reservation.getEndtime().getTime() - currentServerTime;
                if (reservationLength < 0) {
                    Debug.logMessage("GetResourceDetails", "Cleaning up old reservation");
                     MainController.getInstance().smsStopResource(reservation.getResource());
                    response.put(Consts.RESOURCE_STATE, Consts.RESOURCE_NOT_ACTIVE);
                    EntityTransaction tx = em.getTransaction();
                    tx.begin();
                    em.remove(reservation);
                    tx.commit();
                   
                } else {
                    Debug.logMessage("processJsonMessage", "Reservation Length: " + reservationLength);
                    response.put(Consts.RESOURCE_STATE, Consts.RESOURCE_ACTIVE);
                    response.put(Consts.RESERVATION_LENGTH, reservationLength);
                    response.put(Consts.SERVER_TIME, currentServerTime);
                    response.put(Consts.CLIENT_TIME, clientTime);

                    if (user == reservation.getUser()) {
                        response.put(Consts.RESOURCE_OWNERSHIP, Consts.RESOURCE_OWNER);
                    } else {
                        response.put(Consts.RESOURCE_OWNERSHIP, Consts.RESOURCE_NOT_OWNER);
                    }
                }
            } else {
                response.put(Consts.RESOURCE_STATE, Consts.RESOURCE_NOT_ACTIVE);
            }
            em.close();
            return response.toString();

        } catch (JSONException ex) {
            try {
                Logger.getLogger(ActivateResource.class.getName()).log(Level.SEVERE, null, ex);
                response.put(Consts.JSON_MESSAGE_CODE, Consts.RESPONSE_ERROR);

            } catch (JSONException ex1) {
                Logger.getLogger(ActivateResource.class.getName()).log(Level.SEVERE, null, ex1);
            }
            em.close();
            return response.toString();
        }

    }
}
